package com.halflife.nio;



import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ChannelSocket {
    public static void main(String[] args) throws Exception{
        List<SocketChannel> clients = new LinkedList<>();
        ServerSocketChannel ss = ServerSocketChannel.open();
        ss.bind(new InetSocketAddress(9090));
        ss.configureBlocking(false);
        while (true) {
            Thread.sleep(1000);
            SocketChannel client = ss.accept();//no blocking
            if (client == null) {
                System.out.println("null ......");
            }else{
                client.configureBlocking(false);
                System.out.println("client.port: " + client.socket().getPort());
                clients.add(client);
            }
            /**
             * todo 重复利用，防止重复垃圾回收！串行化
             * 就算没有数据传过来都要去读channel 效率有问题！ 用户态到内核态的转化吧！ 系统调用； Ox80 异常！ 中断! 中断控制器 APIC
             * 读数据必然是阻塞的！
             */
            ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
            for (SocketChannel c : clients) {//serilizable  串行化
                int num = c.read(buffer); //0 -1 0//no blocking  不会阻塞
                if (num > 0) {
                    buffer.flip();
                    byte[] results = new byte[buffer.limit()];
                    buffer.get(results);
                    System.out.println(c.getRemoteAddress().toString() + ":" + new String(results));
                    buffer.clear();
                }
            }
        }

    }
}

